<template>
  <div class="recruitment-requirements-container">
    <el-config-provider :locale="zhCn">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="add">
            <el-icon><Plus /></el-icon>
            添加
          </el-button>

          <el-dropdown trigger="click">
            <el-button>
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="item in options" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown trigger="click">
            <el-button>
              删除<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="item in optionss" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                  @click="open">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="toolbar-right">
          <el-input 
            class="search-input" 
            placeholder="搜索数据"
            v-model="searchKeyword" 
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>

          <el-button @click="dialog = true">
            <el-icon><Filter /></el-icon>
            筛选
          </el-button>

          <el-button @click="Sorting">
            <el-icon><Sort /></el-icon>
            {{ toggleSort === 1 ? '升序' : '降序' }}
          </el-button>

          <el-button @click="refresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 卡片容器包装器，用于滚动 -->
      <div class="card-container-wrapper">
        <!-- 卡片 -->
        <div class="card-container">
          <el-card 
            class="box-card" 
            shadow="hover" 
            :key="item.id" 
            v-for="item in page.records" 
            @mouseover.stop="handleMouse(item,true)" 
            @mouseout.stop="handleMouse(item,false)"
            @dblclick="handleCellDblClick(item)">
          <template #header>
            <div class="card-header">
              <el-checkbox 
                v-model="item.checked" 
                :class="item.visbleChecked?'visible-checkbox':'card-checkbox'" 
                @change="handleCheckboxChange(item)">
              </el-checkbox>
              <span class="requirement-id">{{ item.requirementid }}</span>
              <el-dropdown placement="bottom-start">
                <div class="card-actions">
                  <el-button link>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="viewDetails(item)">查看</el-dropdown-item>
                    <el-dropdown-item @click="deleteItem(item)">
                      <el-text type="danger">删除</el-text>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          
          <div class="card-content-wrapper">
            <div class="card-row">
              <el-text class="card-label">需求提交人:</el-text>
              <div class="card-content">
                <el-icon><User /></el-icon>
                {{ item.demandsubmitter }}
              </div>
            </div>

            <div class="card-row">
              <el-text class="card-label">岗位需求:</el-text>
              <div class="card-content">{{ item.jobname }}</div>
            </div>

            <div class="card-row">
              <el-text class="card-label">需求人数:</el-text>
              <div class="card-content">{{ item.numberofpositions }}人</div>
            </div>

            <div class="card-row">
              <el-text class="card-label">创建时间:</el-text>
              <div class="card-content">{{ item.creationdate }}</div>
            </div>

            <div class="card-footer">
              <template v-if="item.status === '进行中'">
                <el-tag type="primary">{{ item.status }}</el-tag>
              </template>
              <template v-else-if="item.status === '已完成'">
                <el-tag type="success">{{ item.status }}</el-tag>
              </template>
              <template v-else-if="item.status === '已结束'">
                <el-tag type="danger">{{ item.status }}</el-tag>
              </template>
              <template v-else>
                <el-tag type="info">{{ item.status }}</el-tag>
              </template>
            </div>
          </div>
        </el-card>
      </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination 
          @current-change="cardList" 
          v-model:current-page="page.current" 
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 30, 40]" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="page.total">
        </el-pagination>
      </div>
    </el-config-provider>
  </div>
  
  <el-dialog title="招聘需求" fullscreen destroy-on-close v-model="AddVisibility">
    <hr>
    <insert></insert>
  </el-dialog>
  
  <!--筛选  -->
  <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
    <div class="demo-drawer__content">
      <el-form :model="form" style="height: 600px;">
        <el-select 
          v-model="screeningStatus" 
          placeholder="筛选" 
          style="width: 100%" 
          placement="bottom">
          <template #label="{ label, value }">
            <span style="font-weight: bold">{{ label }}</span>
          </template>
          <el-option 
            v-for="item in filterStatusData" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" />
        </el-select>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '提交中 ...' : '提交' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
  
  <!-- 详情 -->
  <el-dialog :title="title + `详情`" v-model="dialogVisible" fullscreen destroy-on-close>
    <hr>
    <Details :date="DetailedRequirementsId"></Details>
  </el-dialog>
</template>

<script setup lang="ts">
import request from '@/api/request'
import { watchEffect, onMounted } from 'vue'
import { ref, reactive, computed } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import Insert from './insert.vue'
import Details from './Details.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Filter, Sort, Refresh, MoreFilled, User } from '@element-plus/icons-vue'

const dialog = ref(false); //抽屉
const loading = ref(false) //加载
const AddVisibility = ref(false)//添加招聘需求框可见性
const searchKeyword = ref('') // 搜索关键词
// 是否显示详情
const dialogVisible = ref(false)
const Screening = ref(null) //筛选
const FilterData = ref([ //筛选数据
  { value: '全部', label: '全部' },
  { value: '待面试', label: '待面试' },
  { value: '待入职', label: '待入职' },
])
const screeningStatus = ref(null)
const filterStatusData = ref([ //筛选状态数据
  { value: '全部', label: '全部' },
  { value: '已完成', label: '已完成' },
  { value: '已结束', label: '已结束' },
  { value: '进行中', label: '进行中' },
])
let page = ref({ // 分页数据 
  current: 1, // 当前页
  size: 10, // 每页条数
  total: 0, // 总条数
  records: [] // 数据
})
let toggleSort = ref(1) // 排序
let isChecked = ref(false) // 全选
const savedData = ref([])
// 监听选中项变化并输出到控制台
const handleCheckboxChange = (item) => {
  // 检查 item 是否已存在于 savedData 中
  const index = savedData.value.findIndex(data => data.requirementid === item.requirementid)
  
  if (item.checked) {
    // 如果复选框被选中且数据不存在于数组中，则添加
    if (index === -1) {
      savedData.value.push(item)
    }
  } else {
    // 如果复选框未被选中且数据存在于数组中，则移除
    if (index !== -1) {
      savedData.value.splice(index, 1)
    }
  }
  
  console.log('选中项发生变化:', savedData.value)

  // 获取所有选中的项
  //const selectedItems = page.value.records.filter(record => record.checked);
  //console.log('当前所有选中项:', selectedItems);
  isChecked.value = page.value.records.some(record => record.checked) // 判断是否有选中项
  page.value.records.forEach(item=>{ // 遍历每一行
    item.visbleChecked = isChecked.value // 设置每一行的可见性
  })
}

// 排序
const Sorting = () => {
  toggleSort.value = toggleSort.value === 1 ? 2 : 1 //如果排序状态为1，则切换为2，否则切换为1
  const url =
    toggleSort.value === 1 // 如果排序状态为1 
      ? '/recruitmentBasics/sortByTime'
      : '/recruitmentBasics/sortByTimeDesc'

  request({
    url,
    method: 'get',
    params: {
      pageNum: page.value.current,
      pageSize: page.value.size,
      searchKeyword: searchKeyword.value,
      JobName: searchKeyword.value, // 添加搜索关键词参数
      status: screeningStatus.value // 添加筛选状态参数
    }
  }).then(res => {
    page.value = res.data

  })
}

// 获取数据
const cardList = () => {
  request({
    url: '/recruitmentBasics/find',
    method: 'get',
    params: {
      current: page.value.current, // 当前页
      size: page.value.size, // 每页条数
      total: page.value.total,
      JobName: searchKeyword.value, // 添加搜索关键词参数
      status: screeningStatus.value // 添加筛选状态参数
    }
  }).then(res => {

    page.value = res.data // 更新分页数据
    ElMessage.success('已获取' + page.value.total + '条数据')
    console.log(res);
  }).catch(error => {
    console.error('获取数据失败:', error)
  })
}

// 处理搜索
const handleSearch = () => {
  // 重置到第一页并重新加载数据
  page.value.current = 1
  cardList()
}
cardList()
// // 定时刷新
// setInterval(() => {
//   cardList()
// }, 2000)
const refresh = () => {
  toggleSort.value = 1;
  cardList()
}

//导出下拉框
const options = ref([
  { label: '全部', value: '' },
  { label: '待处理', value: '待处理' },
  { label: '处理中', value: '处理中' },
  { label: '处理完成', value: '处理完成' },
  { label: '处理失败', value: '处理失败' },
])
const add = () => {
  AddVisibility.value = true
}
//招聘需求框取消按钮
const Cancel = () => {
  dialogVisible.value = false
}
const title = ref()
const DetailedRequirementsId = ref() // 招聘需求id
const handleCellDblClick = (item) => {
  ElMessage.success('双击了单元格')
  DetailedRequirementsId.value = item.requirementid // 设置要查看的招聘需求ID
  dialogVisible.value = true; // 显示详情对话框
  title.value = item.requirementid // 设置标题
  console.log(DetailedRequirementsId.value);
}

// 查看详情功能
const viewDetails = (item) => {
  DetailedRequirementsId.value = item.requirementid // 设置要查看的招聘需求ID
  dialogVisible.value = true; // 显示详情对话框
  title.value = item.requirementid // 设置标题
}

// 删除功能
const deleteItem = (itemToDelete) => {
  console.log(itemToDelete);

  ElMessageBox.confirm(
    `确定要删除招聘需求 "${itemToDelete.requirementid}" 吗?`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
    // 用户点击确定，发送删除请求
    request({
      url: '/recruitmentBasics/deleteById',
      method: 'post',
      params: {
        requirementid: itemToDelete.requirementid
      }
    }).then(response => {
      console.log('删除成功:', response);
      ElMessage.success('删除成功');
      // 重新加载数据
      cardList();
    }).catch(error => {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
      // 重新加载数据
      cardList();
    });
  }).catch(() => {
    // 用户点击取消
    ElMessage.info('已取消操作');
  });

}
//删除下拉框
const optionss = ref([
  { label: '删除全部数据', value: '删除全部数据' },
  { label: '删除已选数据', value: '删除已选数据' },
])
// 筛选下拉框
const FilterTheDropDownBox = ref([
  { label: '全部', value: '' },
  { label: '待处理', value: '待处理' },
  { label: '处理中', value: '处理中' },
  { label: '处理完成', value: '处理完成' },
  { label: '处理失败', value: '处理失败' },
])

//删除操作
const open = () => {
  ElMessageBox.confirm(
    '你确定要删除吗?',
    '通知',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消操作',
      })
    })
}
//操作记录下拉框
const optionsss = ref([
  { label: '全部', value: '' },
  { label: '待处理', value: '待处理' },
  { label: '处理中', value: '处理中' },
  { label: '处理完成', value: '处理完成' },
  { label: '处理失败', value: '处理失败' },
])
const form = ref()

const onClick = () => {//筛选提交
  loading.value = true
  if (screeningStatus.value) {
    request({
      url: '/recruitmentBasics/findByStatus',
      method: 'post',
      params: {
        JobName: searchKeyword.value, // 添加搜索关键词参数
        status: screeningStatus.value
      }
    }).then(res => {
      page.value = res.data
      ElMessage.success('已为你找到' + page.value.total + '条数据')
      setTimeout(() => {
        dialog.value = false
      }, 400)
    })
  } else {
    ElMessage.error('你还未选择')
  }
  loading.value = false
  return;
}

//取消
const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

const handleMouse = (item,flag)=>{ //鼠标移入移出
  if(isChecked.value){  //鼠标移入移出
    return; 
  }
  item.visbleChecked = flag 
}
</script>

<style scoped>
.recruitment-requirements-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  padding: 20px;
  background-color: #f5f7fa;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px 20px;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.card-container-wrapper {
  flex: 1;
  overflow: auto;
  margin-bottom: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 20px;
  padding: 10px;
}

.box-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.box-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.requirement-id {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  flex: 1;
  text-align: center;
}

.card-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
}

.card-row {
  display: flex;
  align-items: flex-start;
}

.card-label {
  width: 80px;
  font-weight: 500;
  color: #909399;
  font-size: 13px;
  flex-shrink: 0;
  line-height: 1.5;
}

.card-content {
  flex: 1;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 6px;
  line-height: 1.5;
}

.card-footer {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.card-checkbox,
.card-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.visible-checkbox {
  opacity: 1;
}

.box-card:hover .card-actions {
  opacity: 1;
}

.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px 20px;
}

.demo-drawer__content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.demo-drawer__content .el-form {
  flex: 1;
}

.demo-drawer__footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

/* 响应式设计 - 当屏幕较小时调整每行卡片数量 */
@media (max-width: 1600px) {
  .card-container {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1300px) {
  .card-container {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

@media (max-width: 992px) {
  .card-container {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
  
  .card-container {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }
  
  .card-header {
    padding: 12px 15px;
  }
  
  .card-content-wrapper {
    padding: 15px;
    gap: 12px;
  }
  
  .card-label {
    width: 70px;
    font-size: 12px;
  }
  
  .card-content {
    font-size: 13px;
  }
}
</style>